package com.wlt.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wlt.result.BusException;
import com.wlt.result.CodeEnum;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

@Service
@DubboService
public class FileServiceImpl implements FileService
{
    @Autowired
    private FastFileStorageClient fastFileStorageClient;    // 引进Storage客户端
    
    @Value("${fdfs.fileUrl}")
    private String fileUrl;                                 // Nginx访问FastDFS中文件的路径
    
    @Override
    public String uploadImage (byte[] fileBytes, String fileName)
    {
        if (fileBytes.length != 0)
        {
            try
            {
                // 1.将文件的字节数组转为输入流
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileBytes);
                // 2.获取文件的后缀名，保存到服务器中给它起名
                String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                // 3.上传文件
                StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream,
                                                                       byteArrayInputStream.available(),
                                                                       fileSuffix,
                                                                       null);
                // 4.返回图片路径
                return fileUrl + "/" + storePath.getFullPath();
            }
            catch (Exception e)
            {
                throw new BusException(CodeEnum.UPLOAD_FILE_ERROR);
            }
        }
        else
            throw new BusException(CodeEnum.UPLOAD_FILE_ERROR);
    }
    
    @Override
    public void delete (String filePath)
    {
        fastFileStorageClient.deleteFile(filePath);
    }
}
